import { useMysql } from "../mysql/index.js";
import { MysqlQueryBuilder } from "../mysql/mysql-query-builder.js";
import { TokenCreate, TokenRemove } from "../utils/TokenCheck.js";
// 登录
export const login = async (req, res) => {
  const { username, password } = req.body; // 从请求体中获取用户名和密码
  // 构造 SQL 查询语句
  const sql = MysqlQueryBuilder.select(
    "users",
    ["id", "Name", "username", "password","status","role_id"],
    {
      username: username,
    }
  );
  try {
    const result = await useMysql(sql);

    // 如果没有找到用户
    if (!result || result.length === 0) {
      return res.status(200).send({
        code: 401,
        message: "用户名不存在",
      });
    }
    // 获取用户信息
    const user = result[0];

    // 对比用户状态
    console.log(user.status);
    if (user.status !== '1') {
      return res.status(200).send({
        code: 401,
        message: "用户未激活",
      });
    }
    // 对比明文密码
    if (user.password !== password) {
      return res.status(200).send({
        code: 401,
        message: "密码错误",
      });
    }

    // 生成 Token
    const { token, createdAt, expiresAt } = TokenCreate(
      {
        userId: user.id,
        username: user.username,
      },
      "root",
      "24h"
    );
    // 将Token、创建时间和过期时间存储到白名单(无则添加有则更新)
    const addTokenSql = MysqlQueryBuilder.insert(
      "token",
      {
        user_id: user.id,
        token: token,
        created_at: createdAt,
        expires_at: expiresAt,
      },
      {
        updateOnDuplicate: ["token", "created_at", "expires_at"],
      }
    );
    await useMysql(addTokenSql);

    // 登录成功，返回token
    res.status(200).send({
      code: 200,
      message: "登录成功",
      token: token,
      name: user.Name,
      id:user.id,
      role_id:user.role_id,
    });
  } catch (err) {
    console.error("登录失败:", err);
    res.status(500).send({
      code: 500,
      message: "服务器内部错误",
    });
  }
};
//退出登录，删除 Token
export const logout = async (req, res) => {
  try {
    // 从请求头中提取 Token
    const token = req.headers["authorization"].split(" ")[1];

    // 调用 TokenRemove 方法
    const result = await TokenRemove(token);

    if (result.success) {
      res.status(200).send({
        code: 200,
        message: result.message,
      });
    } else {
      res.status(400).send({
        code: 400,
        message: result.message,
      });
    }
  } catch (error) {
    res.status(500).send({
      code: 500,
      message: "退出登录失败: " + error.message,
    });
  }
};
// 注册用户
export const sign = async (req, res) => {
  const { username, password, Name = "", phoneA = "", email = "" } = req.body; // 从请求体中获取注册信息
  // 构造 SQL 插入语句
  const sql = MysqlQueryBuilder.insert(
    "users",
    {
      username: username,
      password: password,
      Name: Name,
      phoneA: phoneA,
      email: email,
    },
  );

  try {
    // 执行插入操作
    const result = await useMysql(sql, [
      username,
      password,
      Name,
      phoneA,
      email,
    ]);

    // 注册成功
    res.status(200).send({
      code: 200,
      message: "注册成功",
      data: {
        username,
        Name,
        phoneA,
        email,
      },
    });
  } catch (err) {
    console.error("注册失败:", err);

    // 判断是否是由于用户名重复导致的注册失败
    if (err.code === "ER_DUP_ENTRY") {
      res.status(200).send({
        code: 400,
        message: "用户名已存在",
      });
    } else {
      res.status(500).send({
        code: 500,
        message: "服务器内部错误",
      });
    }
  }
};
